package 双指针;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class _008 {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> ret =new ArrayList<>();
        int n=nums.length;
        Arrays.sort(nums);
        for(int i=0;i<n;){
            for(int j=i+1;j<n;){
                int left=j+1;
                int right=n-1;
                long aim=(long)target-nums[i]-nums[j];
                while(left<right){
                    int sum=nums[left]+nums[right];
                    if(sum==aim){
                        ret.add(new ArrayList<Integer>(Arrays.asList(nums[i],nums[j],nums[left],nums[right])));
                        left++;
                        while(left<right && nums[left]==nums[left-1]){
                            left++;
                        }
                        right--;
                        while(left<right && nums[right]==nums[right+1]){
                            right--;
                        }
                    }else if(sum>aim){
                        right--;
                    }else{
                        left++;
                    }
                }
                j++;
                while(j<n&&nums[j]==nums[j-1]){
                    j++;
                }
            }
            i++;
            while(i<n&&nums[i]==nums[i-1]){
                i++;
            }
        }
        return ret;
    }
}
